<?php
namespace app\beautiful\controller\miniapp\staff;
use app\beautiful\logic\LogsLogic;
use app\beautiful\model\CouponModel;
use app\beautiful\model\logs\MemberBalanceLogsModel;
use app\beautiful\model\logs\MemberCouponLogsModel;
use app\beautiful\model\logs\MemberIntegralLogsModel;
use app\beautiful\model\member\MemberBalanceModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\member\MemberIntegralModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\order\BuyOrderModel;
use app\beautiful\logic\order\OrderLogic;
use app\beautiful\logic\PartnerLogic;
use app\beautiful\model\member\MemberOnceCardItemModel;
use app\beautiful\model\member\MemberOnceCardModel;
use app\beautiful\model\member\MemberProjectModel;
use app\beautiful\model\member\MemberSnapUpModel;
use app\BaseController;

use app\beautiful\model\project\OnceCardModel;
use app\beautiful\logic\printer\PrinterLogic;
use think\facade\Db;
use app\beautiful\logic\MemberWalletLogic;
use app\beautiful\model\logs\ProjectWriteOffModel;
use app\beautiful\model\logs\ApplyLogsModel;

class Member extends BaseController{
    public function getMemberInfo()
    {
        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');
        if($member->is_delete != 0) return $this->error('会员不存在');
        if($member->shop_id != $this->request->shopId) return $this->error('会员不存在');
        $member->append(['hidden_mobile']);
        $today=date("Y-m-d",$this->request->time());

        $balance = MemberBalanceModel::where([
                ['shop_id','=',$this->request->shopId],
                ['member_id','=',$member_id],
                ['valid_bg_time','<=',$this->request->time()]
            ])->sum('remain_balance') ?? 0;

        $integral = MemberIntegralModel::where([
                ['shop_id','=',$this->request->shopId],
                ['member_id','=',$member_id],
                ['expire_time','>',$this->request->time()]
            ])->sum('remain_integral') ?? 0;

        $coupon_count = MemberCouponModel::where([
                ['shop_id','=',$this->request->shopId],
                ['member_id','=',$member_id],
            ])->count() ?? 0;

        $snap_up_count=MemberSnapUpModel::where([
                ['shop_id','=',$this->request->shopId],
                ['member_id','=',$member_id],
                ['status','=',1],
                ['valid_end_time','>=',$today]
            ])->count() ?? 0;

        $once_card_count=MemberOnceCardModel::where([
                ['shop_id','=',$this->request->shopId],
                ['member_id','=',$member_id],
                ['status','=',1],
                ['valid_end_time','>=',$today]
            ])->count() ?? 0;

        $detail=[
            'member_id'=>$member->member_id,
            'nick_name'=>$member->nick_name,
            'is_vip'=>$member->level ? 1 : 0,
            'level_name'=>$member->level ? $member->level->name : '普通会员',
            'hidden_mobile'=>$member->hidden_mobile,
            'face'=>$member->face,
            'level_discount'=>$member->level ? $member->level->discount : 10,
            'balance'=>$balance,
            'integral'=>$integral,
            'coupon_count'=>$coupon_count,
            'snap_up_count'=>$snap_up_count,
            'once_card_count'=>$once_card_count,
        ];
        $return=[
            'detail'=>$detail,
        ];
        return $this->success($return);

    }

    public function getMemberInfoFromMobile()
    {
        $mobile = $this->request->param('mobile');
        if(empty($mobile) || !is_mobile($mobile)){
            return $this->error('请输入手机号');
        }

        if (null === $member = MemberModel::where([
                ['mobile','=',$mobile],
                ['shop_id','=',$this->request->shopId],
                ['status','=',1],
                ['is_delete','=',0]
            ])->find()) {
            return $this->error('会员不存在');
        }

        $detail=[
            'member_id'=>$member->member_id,
            'nick_name'=>$member->nick_name,
            'is_vip'=>$member->level ? 1 : 0,
            'level_name'=>$member->level ? $member->level->name : '普通会员',
            'hidden_mobile'=>$member->hidden_mobile,
            'face'=>$member->face,
            'level_discount'=>$member->level ? $member->level->discount : 10,
        ];
        $return=[
            'detail'=>$detail,
        ];
        return $this->success($return);
    }

    public function balanceRecharge()
    {
        //判断权限
        if (!in_array(2, $this->request->staff->add_value_jurisdiction)) {
            return $this->error('您没有余额充值的权限');
        }

        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');
        if($member->is_delete != 0)  return $this->error('会员不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error('会员不存在');

        $balance= $this->request->param('balance/f',0);
        $give_balance =$this->request->param('give_balance/f',0);
        if($balance <=0 ) return $this->error('请填写充值金额，且金额不能小于等于0');

        Db::startTrans();
        try{
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member_id);
            $res = $MemberWalletLogic->addBalance($balance, $give_balance, 2,'', $this->request->staffId);
            if($res == false){
                Db::rollback();
                return $this->error($MemberWalletLogic->getError());
            }
            Db::commit();
            return $this->success('操作成功');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function writeOffBalance()
    {
        //判断权限
        if ($this->request->staff->write_off_jurisdiction !=1) {
            return $this->error('您没有核销的权限');
        }

        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');
        if($member->is_delete != 0)  return $this->error('会员不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error('会员不存在');

        $balance= $this->request->param('balance/f',0);
        $original_deduction =$this->request->param('original_deduction/f',0);
        if($balance <=0 ) return $this->error('请填写扣除金额，且金额不能小于等于0');
        if($original_deduction <= 0) return $this->error('请填写原本扣除金额，金额不能小于等于0');
        if($original_deduction < $balance) return $this->error('原本扣除的金额不能小于实际扣除的金额');

        $remarks=$this->request->param('remarks');

        Db::startTrans();
        try{
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member_id);
            $res = $MemberWalletLogic->useBalance($balance, $original_deduction, 6,$remarks, $this->request->staffId);
            if($res == false){
                Db::rollback();
                return $this->error($MemberWalletLogic->getError());
            }
            Db::commit();
            return $this->success('操作成功');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }

    }

    public function integralRecharge()
    {
        //判断权限
        if (!in_array(3, $this->request->staff->add_value_jurisdiction)) {
            return $this->error('您没有增加积分的权限');
        }

        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');
        if($member->is_delete != 0)  return $this->error('会员不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error('会员不存在');

        $integral= $this->request->param('integral/d',0);
        if($integral <=0 ) return $this->error('请填写充值积分，且积分不能小于等于0');


        Db::startTrans();
        try{
            
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member_id);
            $res = $MemberWalletLogic->addIntegal($integral, 1,'', $this->request->staffId);
            if($res == false){
                Db::rollback();
                return $this->error($MemberWalletLogic->getError());
            }
          
            Db::commit();
            return $this->success('操作成功');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function writeOffIntegral()
    {
        //判断权限
        if ($this->request->staff->write_off_jurisdiction !=1) {
            return $this->error('您没有核销的权限');
        }

        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');
        if($member->is_delete != 0)  return $this->error('会员不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error('会员不存在');

        $integral= $this->request->param('integral/d',0);
        if($integral <=0 ) return $this->error('请填写充值积分，且积分不能小于等于0');

        $remarks=$this->request->param('remarks');

        Db::startTrans();
        try{
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member_id);
            $res = $MemberWalletLogic->useIntegral($integral, 4,$remarks, $this->request->staffId);
            if($res == false){
                Db::rollback();
                return $this->error($MemberWalletLogic->getError());
            }
            Db::commit();
            return $this->success('操作成功');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function chooseCoupon()
    {
        $today=date("Y-m-d",$this->request->time());
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['status','=',1],
            ['end_time','>=',$today]
        ];

        $datas=CouponModel::where($where)
            ->order(['update_time'=>'desc','add_time'=>'desc'])
            ->field('coupon_id,name,valid_bg_time,valid_end_time,coupon_money,money_limit')
            ->limit($this->request->limit)->page($this->request->page)
            ->select()->toArray();
        return $this->success(['datas'=>$datas]);
    }

    public function sendCoupon()
    {
        //判断权限
        if (!in_array(4, $this->request->staff->add_value_jurisdiction)) {
            return $this->error('您没有送券的权限');
        }

        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');
        if($member->is_delete != 0)  return $this->error('会员不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error('会员不存在');

        $coupon_ids = $this->request->param('coupon_ids/a',[]);
        if(empty($coupon_ids)) return $this->error('请选择优惠券');
        $coupon_data=CouponModel::where([
            ['coupon_id','in',$coupon_ids],
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['status','=',1],
            ['end_time','>=',date("Y-m-d",$this->request->time())]
        ])->field('coupon_id,name,valid_bg_time,valid_end_time,coupon_money,money_limit,add_time')
            ->select()->toArray();
        if(empty($coupon_data)) return $this->error('请选择优惠券');



        foreach ($coupon_data as $k => $coupon){
            $member_coupon_model = new MemberCouponModel();
            $member_coupon_data=[
                'shop_id'=>$this->request->shopId,
                'member_id'=>$member_id,
                'type_id'=>2,
                'coupon_id'=>$coupon['coupon_id'],
                'name'=>$coupon['name'],
                'coupon_money'=>$coupon['coupon_money'],
                'money_limit'=>$coupon['money_limit'],
                'valid_bg_time'=>$coupon['valid_bg_time'],
                'valid_end_time'=>$coupon['valid_end_time'],
            ];
            $member_coupon_model->save($member_coupon_data);

            LogsLogic::coupon($this->request->shopId,$member_id,1,2,$member_coupon_model->member_coupon_id,'',$this->request->staffId);
        }

        return $this->success('送券成功');
    }

    public function getMemberCouponList()
    {
        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');
        if($member->is_delete != 0) return $this->error('会员不存在');
        if($member->shop_id != $this->request->shopId) return $this->error('会员不存在');
        $member->append(['hidden_mobile']);

        $where=[
            ['shop_id','=',$this->request->shopId]
        ];
        if(!empty($member_id)) $where[]=['member_id','=',$member_id];

        $coupons = MemberCouponModel::where($where)
            ->order(['add_time'=>'desc'])
            ->field('member_coupon_id,name,valid_bg_time,valid_end_time,coupon_money,money_limit,status')
            ->limit($this->request->limit)->page($this->request->page)
            ->select()
            ->append(['is_expire'])
            ->toArray();

        $return['coupons']=$coupons;
        if($this->request->page==1){
            $member_info=[
                'member_id'=>$member->member_id,
                'nick_name'=>$member->nick_name,
                'is_vip'=>$member->level ? 1 : 0,
                'level_name'=>$member->level ? $member->level->name : '普通会员',
                'hidden_mobile'=>$member->hidden_mobile,
                'face'=>$member->face,
                'level_discount'=>$member->level ? $member->level->discount : 10,
            ];
            $return['member_info']=$member_info;
        }

        return $this->success($return);
    }

    public function writeOffCoupon()
    {
        //判断权限
        if ($this->request->staff->write_off_jurisdiction !=1) {
            return $this->error('您没有核销的权限');
        }

        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');
        if($member->is_delete != 0)  return $this->error('会员不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error('会员不存在');

        $member_coupon_id =$this->request->param('member_coupon_id/d',0);
        if(null === $memberCoupon = MemberCouponModel::find($member_coupon_id)) return $this->error('优惠券不存在');
        if($memberCoupon->shop_id != $this->request->shopId) return $this->error('优惠券不存在');
        if($memberCoupon->member_id != $member_id) return $this->error('优惠券不存在');
        if($memberCoupon->status != 0) return $this->error('该优惠券已使用过了');
        if($memberCoupon->valid_end_time <date("Y-m-d")) return $this->error('该优惠券已过期');

        $memberCoupon->status=1;
        $memberCoupon->save();

        LogsLogic::coupon($this->request->shopId,$member_id,-1,6,$member_coupon_id,'',$this->request->staffId);
        return $this->success('核销成功');
    }

    public function getMemberLogsList()
    {
        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');
        if($member->is_delete != 0)  return $this->error('会员不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error('会员不存在');

        $type=$this->request->param('type/d',1);
        if(!in_array($type,[1,2,3,4,5,6])) $type=1;
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['member_id','=',$member_id]
        ];
        switch ($type){
            case 1:
               $datas=MemberBalanceLogsModel::where($where)
                   ->order(['add_time'=>'desc'])
                   ->field('type,info,original_deduction,balance,give_balance,remarks,operate_mobile,operate_name,add_time')
                   ->limit($this->request->limit)
                   ->page($this->request->page)
                   ->select()
                   ->append(['add_time_format','operate_hidden_mobile'])
                   ->toArray();
            break;
            case 2:
                $datas=MemberIntegralLogsModel::where($where)
                    ->order(['add_time'=>'desc'])
                    ->field('type,info,integral,remarks,operate_mobile,operate_name,add_time')
                    ->limit($this->request->limit)
                    ->page($this->request->page)
                    ->select()
                    ->append(['add_time_format','operate_hidden_mobile'])
                    ->toArray();
                break;
            case 3:
                $datas=MemberCouponLogsModel::with(['membercoupon'=>function($query){
                    $query->field('member_coupon_id,coupon_money,name');
                }])->where($where)
                    ->order(['add_time'=>'desc'])
                    ->field('type,info,member_coupon_id,operate_mobile,operate_name,add_time')
                    ->limit($this->request->limit)
                    ->page($this->request->page)
                    ->select()
                    ->append(['add_time_format','operate_hidden_mobile'])
                    ->toArray();
                break;
            case 5: //办理项目记录
                $datas = ApplyLogsModel::where($where)->order(['add_time'=>'desc'])->limit($this->request->limit)
                    ->page($this->request->page)
                    ->select()
                    ->append(['add_time_format','operate_hidden_mobile'])
                    ->toArray();
                break;
            case 6://项目核销记录
                $datas = ProjectWriteOffModel::where($where)->order(['add_time'=>'desc'])->limit($this->request->limit)
                    ->page($this->request->page)
                    ->select()
                    ->append(['add_time_format','operate_hidden_mobile'])
                    ->toArray();
                break;
            default :
                $where[]=['is_paid','=',1];
                $datas=BuyOrderModel::where($where)
                    ->order(['add_time'=>'desc'])
                    ->field('balance,vip_balance,coupon_money,integral_balance,pay_type,use_integral,add_time')
                    ->limit($this->request->limit)
                    ->page($this->request->page)
                    ->select()
                    ->append(['add_time_format','price','pay_type_mean'])
                    ->toArray();
                break;
        }

        return $this->success(['datas'=>$datas]);
    }


    public function getMemberSnapupList()
    {
        $type = $this->request->param('type/d');
        $member_id=$this->request->param('member_id/d',0);
        $where = [
            ['shop_id','=',$this->request->shopId],
            ['member_id','=', $member_id]
        ];
        $today = date('Y-m-d',time());

        if($type == 0){
            $where[] = ['status','=',1];
            $where[] = ['valid_end_time','>=',$today];
            $query = MemberSnapUpModel::where($where);
        }else{

            $where1 = $where;
            $where2 = $where;
            $where1[] = ['status','=',8];
            $where2[] =  ['valid_end_time','<',$today];

            $query = MemberSnapUpModel::whereOr([$where1,$where2]);
        }
        $datas = $query->order(['member_snap_up_id'=>'desc'])->page($this->request->page)->limit($this->request->limit)->select()->append(['status_another','add_time_format'])->toArray();
        return $this->success(['datas'=>$datas]);
    }

    public function writeOffSnapup()
    {
        //判断权限
        if ($this->request->staff->write_off_jurisdiction !=1) {
            return $this->error('您没有核销的权限');
        }

        $today=date("Y-m-d",$this->request->time());

        $member_id=$this->request->param('member_id/d',0);
        $member_snap_up_id=$this->request->param('member_snap_up_id/d',0);
        $num=$this->request->param('num/d',0);
        $remark=$this->request->param('remark');

        if($member_id == 0)  return $this->error('会员不存在');
        if($member_snap_up_id ==0) return $this->error('抢购订单不存在');
        if($num <= 0) return $this->error('核销次数不能小于0');

        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');
        if($member->is_delete != 0)  return $this->error('会员不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error('会员不存在');

        if(null === $member_snap_up = MemberSnapUpModel::find($member_snap_up_id)) return $this->error('抢购订单不存在');
        if($member_snap_up->shop_id != $this->request->shopId) return $this->error('抢购订单不存在');
        if($member_snap_up->status != 1) return $this->error('抢购订单不存在');
        if($member_snap_up->member_id != $member_id) return $this->error('抢购订单不存在');
        if($member_snap_up->valid_end_time < $today) return $this->error('抢购订单已过期');

        if(null === $member_project = MemberProjectModel::where([
                ['member_id','=',$member_snap_up->member_id],
                ['source','=','snap_up'],
                ['project_id','=',$member_snap_up->project_id],
                ['member_snap_up_id','=',$member_snap_up_id],
                ['total_num','=',$member_snap_up->total_num],
                ['remain_num','=',$member_snap_up->remain_num]
            ])->find()){
            return $this->error('抢购订单不存在');
        }



        $remain_num=$member_snap_up->remain_num - $num;
        if($remain_num < 0) return $this->error('抢购订单的剩余数量不够这次核销');
        Db::startTrans();
        try{
            //处理我的抢购
            $member_snap_up->remain_num = $remain_num;
            if($remain_num==0) $member_snap_up->status=8;
            $member_snap_up->save();
            //处理我的项目
            $member_project->remain_num = $remain_num;
            $member_project->save();

            //添加核销记录
            $res= LogsLogic::project($this->request->shopId,$member->member_id,'snap_up',$member_snap_up_id,$num,$remain_num,$remark,1,$this->request->staffId);
            if(!$res){
                Db::rollback();
                return $this->error('核销失败');
            }

            //打印机
            $printer_logic =new PrinterLogic($this->request->shopId);
            $printer_logic->print('snapUpOrderWriteOff',$res);
            
            Db::commit();
            return $this->success('核销成功');
        }catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }


    public function writeOffOncecard()
    {
        //判断权限
        if ($this->request->staff->write_off_jurisdiction !=1) {
            return $this->error('您没有核销的权限');
        }

        $today=date("Y-m-d",$this->request->time());

        $member_id=$this->request->param('member_id/d',0);
        $member_once_card_item_id=$this->request->param('member_once_card_item_id/d',0);
        $num=$this->request->param('num/d',0);
        $remark=$this->request->param('remark');

        //简单的判断参数
        if($member_id == 0)  return $this->error('会员不存在');
        if($member_once_card_item_id ==0) return $this->error('次卡不存在');
        if($num <= 0) return $this->error('核销次数不能小于0');
        //判断用户
        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');
        if($member->is_delete != 0)  return $this->error('会员不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error('会员不存在');
        //判断次卡项目
        if(null === $member_once_card_item = MemberOnceCardItemModel::find($member_once_card_item_id)) return $this->error('次卡不存在');
        if($member_once_card_item->shop_id != $this->request->shopId) return $this->error('次卡不存在');
        if($member_once_card_item->member_id != $member_id) return $this->error('次卡不存在');
        //判断次卡
        if(null === $member_once_card = MemberOnceCardModel::find($member_once_card_item->member_once_card_id)) return $this->error('次卡不存在');
        if($member_once_card->status != 1) return $this->error('次卡的状态不在待消费');
        if($member_once_card->valid_end_time < $today) return $this->error('次卡已过期');
        if($member_once_card->member_id != $member_id) return $this->error('次卡不存在');
        //判断项目
        if(null === $member_project = MemberProjectModel::where([
                ['member_id','=',$member_once_card_item->member_id],
                ['source','=','once_card'],
                ['project_id','=',$member_once_card_item->project_id],
                ['member_once_card_item_id','=',$member_once_card_item_id],
                ['total_num','=',$member_once_card_item->total_num],
                ['remain_num','=',$member_once_card_item->remain_num]
            ])->find()){
            return $this->error('次卡不存在');
        }



        $remain_num=$member_once_card_item->remain_num - $num;
        if($remain_num < 0) return $this->error('抢购订单的剩余数量不够这次核销');
        Db::startTrans();
        try{
            //处理我的次卡项目
            $member_once_card_item->remain_num = $remain_num;
            $member_once_card_item->save();

            //处理次卡状态
            if(null === MemberOnceCardItemModel::where([
                    ['shop_id','=',$this->request->shopId],
                    ['member_id','=',$member->member_id],
                    ['member_once_card_id','=',$member_once_card->member_once_card_id],
                    ['remain_num','>',0]
                ])->find()){
                $member_once_card->status=8;
                $member_once_card->save();
            }
            //处理我的项目
            $member_project->remain_num = $remain_num;
            $member_project->save();

            //添加核销记录
            $res=LogsLogic::project($this->request->shopId,$member->member_id,'once_card',$member_once_card_item_id,$num,$remain_num,$remark,1,$this->request->staffId);
            if(!$res){
                Db::rollback();
                return $this->error('核销失败');
            }

            //打印机
            $printer_logic =new PrinterLogic($this->request->shopId);
            $printer_logic->print('onceCardOrderWriteOff',$res);
            Db::commit();
            return $this->success('核销成功');
        }catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function chooseOnceCard()
    {
        //判断极限
        if (!in_array(10, $this->request->staff->add_value_jurisdiction)) {
            return $this->error('您没有办理次卡的权限');
        }

        $name=$this->request->param('name');
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['status','=',1]
        ];
        if(!empty($name)) $where[]=['name','=',$name];


        $once_card_model = new OnceCardModel();
        $order=['sort'=>'desc','add_time'=>'desc'];
        $field='once_card_id,name,cover_img,price,worth,is_flash_sale,flash_num,flash_price,start_time,end_time,take_count';
        $append=['is_flash_sale_expire','flash_sale_djs'];
        $datas=$once_card_model->where($where)
            ->order($order)
            ->field($field)
            ->limit($this->request->limit)
            ->page($this->request->page)
            ->select()
            ->append($append)
            ->toArray();
        $return['datas']=$datas;

        return $this->success($return);
    }

    public function applyOnceCard()
    {
        //判断极限
        if (!in_array(10, $this->request->staff->add_value_jurisdiction)) {
            return $this->error('您没有办理次卡的权限');
        }

        $member_id=$this->request->param('member_id/d',0);
        $once_card_id=$this->request->param('once_card_id/d',0);
        $total_price=$this->request->param('total_price/f',0);
        $need_pay=$this->request->param('price/f',0);


        //判断传来的参数
        if($member_id ==0) return $this->error('会员不存在');
        if($once_card_id == 0) return $this->error('次卡不存在');
        if(empty($total_price) || $total_price <= 0) return $this->error('参数错误');
        if(empty($need_pay) || $need_pay <= 0) return $this->error('请输入实际价格，且不能小于0');

        $params=[
            'member_id'=>$member_id,
            'total_price'=>$total_price,
            'once_card_id'=>$once_card_id,
            'need_pay'=>$need_pay,
            'operate_type'=>1,
            'operate_id'=>$this->request->staffId,
        ];

        Db::startTrans();
        try{
            $order_logic = OrderLogic::init($this->request->shopId);
            $order_logic['once_card']->apply($params);

            //记录推广员业绩
            $PartnerLogic = new PartnerLogic($this->request->shopId);
            $PartnerLogic->commission($member_id,$need_pay);
            Db::commit();
            return $this->success('办理成功');
        }catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    //获取我的次卡列表
    public function getMemberOncecardList(){
        $type = $this->request->param('type/d');
        $member_id=$this->request->param('member_id/d',0);
        $where = [
            ['shop_id','=',$this->request->shopId],
            ['member_id','=', $member_id]
        ];
        $today = date('Y-m-d',time());

        if($type == 0){
            $where[] = ['status','=',1];
            $where[] = ['valid_end_time','>=',$today];
            $query = MemberOnceCardModel::where($where);
        }else{

            $where1 = $where;
            $where2 = $where;
            $where1[] = ['status','=',8];
            $where2[] =  ['valid_end_time','<',$today];

            $query = MemberOnceCardModel::whereOr([$where1,$where2]);
        }
        $datas = $query->with(['items'])->order(['member_once_card_id'=>'desc'])->page($this->request->page)->limit($this->request->limit)->select()->append(['status_another'])->toArray();
        return $this->success(['datas'=>$datas]);
    }
}
